/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sree.tali.filter;

import com.sree.tali.buscomp.DisplayBusComp;
import com.sree.tali.buscomp.DisplayBusCompImpl;
import com.sree.tali.plugin.HibernatePlugin;
import com.sree.tali.pojo.LoginForm;
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.internal.SessionImpl;

// Implements Filter class
public class LoginFilter implements Filter {
      private  ServletContext application= null;
    public void init(FilterConfig config)
            throws ServletException {
      // Get init parameter 
       application =config.getServletContext();
        //Print the init parameter 
    }

    public void doFilter(ServletRequest request,
            ServletResponse response,
            FilterChain chain)
            throws java.io.IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;
   

        // Get the IP address of client machine.   
        String ipAddress = request.getRemoteAddr();
        SessionFactory localSessionFactory =null;

        // Log the IP address and current timestamp.
        System.out.println("IP " + ipAddress);
        boolean isValid=false;
        LoginForm loginform = (LoginForm) httpReq.getSession().getAttribute("loginform");
        if (loginform != null) {
            DisplayBusComp localDisplayBusCompImpl = new DisplayBusCompImpl();
             localSessionFactory = (SessionFactory) application.getAttribute(HibernatePlugin.KEY_NAME);

            if (localDisplayBusCompImpl.AuthenticateIp(localSessionFactory.openSession(), request.getRemoteAddr())) {
                 isValid = localDisplayBusCompImpl.Authenticate(localSessionFactory.openSession(), loginform);
            }
        }

        //chain.doFilter(request,response);
        if(!isValid){
        request.getRequestDispatcher("/SreeLogin.jsp").forward(request, response);
        }
        else
        {
            List<String> rolesList = getRolesForUser(loginform.getJ_username(),localSessionFactory.openSession());
            String uri = httpReq.getParameter("method");//getRequestURI();
           /* System.out.println(rolesList);
            System.out.println(uri.toUpperCase());
            System.out.println(uri.toUpperCase().contains("uploadImagePage".toUpperCase()));
            System.out.println(uri.toUpperCase().contains("viewarticlespage".toUpperCase()));
            System.out.println(uri.toUpperCase().contains("addimagepage".toUpperCase()));
            System.out.println(!(uri.toUpperCase().contains("uploadImagePage".toUpperCase())
                    ||uri.toUpperCase().contains("viewarticlespage".toUpperCase())
                    ||uri.toUpperCase().contains("addimagepage".toUpperCase())));*/


            if(!rolesList.contains("ADMIN")&& 
                    !(uri.toUpperCase().contains("uploadImagePage".toUpperCase())
                    ||uri.toUpperCase().contains("viewarticlespage".toUpperCase())
                    ||uri.toUpperCase().contains("addimagepage".toUpperCase())
                    ||uri.toUpperCase().contains("uploadImages".toUpperCase())
                    ||uri.toUpperCase().contains("viewArticles".toUpperCase())
                    ||uri.toUpperCase().contains("getSubfoldersForImages".toUpperCase())
                    ||uri.toUpperCase().contains("addImages".toUpperCase())
                    ||uri.toUpperCase().contains("getSubfolders".toUpperCase())))
            {
                httpReq.getSession().invalidate();
                request.getRequestDispatcher("/SreeLogin.jsp").forward(request, response);
            }
             else
                chain.doFilter(request,response);
        }
        //response.getWriter().
        
    }

    public void destroy() {
        /* Called before the Filter instance is removed 
         from service by the web container*/
    }
    
    public List<String> getRolesForUser(String userName,Session session)
  //          private List<String> getArticleTypes()

  {
      List<String> userRolesList = new ArrayList<String>();
      Connection localConnection =null;
      //SessionFactory localSessionFactory = (SessionFactory)this.servlet.getServletContext().getAttribute(HibernatePlugin.KEY_NAME); 
      // Session session = localSessionFactory.openSession();
       try
    {
       localConnection = ((SessionImpl)session).connection();
      String qry= "select distinct ru.role_name from role_user ru  where  ru.user_name = '"+userName.trim()+"'";
      Statement localStatement = localConnection.createStatement();
      ResultSet localResultSet = localStatement.executeQuery(qry.toUpperCase());
      while (localResultSet.next())
      {
        userRolesList.add(localResultSet.getString(1).toUpperCase());
      }
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
       finally{
       if(localConnection!=null){
           try{
           localConnection.close();
           }
           catch(Exception ex)
           {
               ex.printStackTrace();
           }
       }
       }
   
      return userRolesList ;
      //return new ArtilceTypesConstants().getArticleTypes();
  }
}
